package com.qcxk.yuqian.rtu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.qcxk.yuqian.rtu.controller.model.page.Pagination;
import com.qcxk.yuqian.rtu.controller.model.query.*;
import com.qcxk.yuqian.rtu.controller.model.response.PageResponse;
import com.qcxk.yuqian.rtu.controller.model.response.Response;
import com.qcxk.yuqian.rtu.entity.DeviceAlarmDetail;
import com.qcxk.yuqian.rtu.entity.Rtu;
import com.qcxk.yuqian.rtu.entity.RtuOriginalData;
import com.qcxk.yuqian.rtu.entity.VbHistory;
import com.qcxk.yuqian.rtu.mapper.RtuRunInfoMapper;
import com.qcxk.yuqian.rtu.service.*;
import com.qcxk.yuqian.system.utils.DataUtils;
import com.qcxk.yuqian.system.utils.RedisUtil;
import org.springframework.web.bind.annotation.RequestMapping;

import com.qcxk.yuqian.system.component.behaviour.BehaviourOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qcxk.yuqian.system.component.constant.SystemConstant;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @auther lp
 * @create 2021-11-15 03:23:05
 * @describe 前端控制器
 */
@RestController
@RequestMapping("/bigscreen")
public class RtuDataController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IRtuDataService rtuDataService;
    @Autowired
    private IRtuHisDataService rtuHisDataService;
    @Autowired
    private IDeviceDebugService deviceDebugService;
    @Autowired
    private IRtuRunInfoService rtuRunInfoService;
    @Autowired
    private RtuRunInfoMapper rtuRunInfoMapper;
    @Autowired
    private IDeviceAlarmService deviceAlarmService;
    @Autowired
    private IRtuService rtuService;
    @Autowired
    private IVbHistoryService vbHistoryService;
    @BehaviourOperator(desc = "查询设备总览")
    @RequestMapping(value = "/countDeviceNum11")
    public Response countDeviceNum() {
        JSONObject json = new JSONObject();
        json.put("alarmNum", 9);
        json.put("offlineNum",123);
        json.put("totalNum", 333);
        json.put("onlineNum", 44);

        return Response.build(json).success();
    }
    @BehaviourOperator(desc = "查询地图")
    @RequestMapping(value = "/centermap")
    public Response centermap() {
        JSONObject json = new JSONObject();
        List<HashMap> dataList=new ArrayList();

        for(int i=0; i<=2 ;i++){
            HashMap<String,Object> m=new HashMap();
            if (i==0){
                m.put("name","安徽省");
                m.put("value",123);
            }
            if (i==1){
                m.put("name","江苏省");
                m.put("value",12);
            }
            if (i==2){
                m.put("name","黑龙江省");
                m.put("value",1123);
            }

            dataList.add(m);
        }

        json.put("dataList", dataList);
        json.put("regionCode", "china");



        return Response.build(json).success();
    }
    @BehaviourOperator(desc = "查询实时数据")
    @RequestMapping(value = "/sssj")
    public Response sssj() {

        List<HashMap> dataList=new ArrayList();

        for(int i=0; i<=2 ;i++){
            HashMap<String,Object> m=new HashMap();
            if (i==0){
                m.put("alertdetail",12);
                m.put("alertname",12);
                m.put("alertvalue",12);
                m.put("cityName",12);
                m.put("countyName",12);
                m.put("createtime","2022-04-19 08:38:33");
                m.put("deviceid",151235);
                m.put("gatewayno","01");
                m.put("phase",12);
                m.put("provinceName",12);
                m.put("sbInfo",12);
                m.put("terminalno",12);
            }
            if (i==1){
                m.put("alertdetail",12);
                m.put("alertname",12);
                m.put("alertvalue",12);
                m.put("cityName",12);
                m.put("countyName",12);
                m.put("createtime","2022-04-19 08:38:33");
                m.put("deviceid",123124);
                m.put("gatewayno","03");
                m.put("phase",12);
                m.put("provinceName",12);
                m.put("sbInfo",12);
                m.put("terminalno",12);
            }
            if (i==2){
                m.put("alertdetail",12);
                m.put("alertname",12);
                m.put("alertvalue",12);
                m.put("cityName","齐齐哈尔市");
                m.put("countyName","龙江县");
                m.put("createtime","2022-04-19 08:38:33");
                m.put("deviceid",12);
                m.put("gatewayno","02");
                m.put("phase",12);
                m.put("provinceName","黑龙江省");
                m.put("sbInfo",12);
                m.put("terminalno",12);
                m.put("pressure",3.56);
                m.put("temperature",22.81);
                m.put("momentMarkCon",15392.18);
                m.put("cumulative",43816328.00);
                m.put("beforeCumulative",654321.00);

            }

            dataList.add(m);
        }
        JSONObject json = new JSONObject();
        json.put("list", dataList);
        return Response.build(json).success();
    }
    @BehaviourOperator(desc = "设备提醒")
    @RequestMapping(value = "/sbtx")
    public Response sbtx( ) {

        List<HashMap> dataList=new ArrayList();

        for(int i=0; i<=2 ;i++){
            HashMap<String,Object> m=new HashMap();
            if (i==0){
                m.put("cityName",12);
                m.put("countyName",12);
                m.put("createTime","2022-04-19 08:38:33");
                m.put("deviceid",151235);
                m.put("gatewayno","01");
                m.put("onlineState",1);
                m.put("provinceName",12);

            }
            if (i==1){
                m.put("cityName",12);
                m.put("countyName",12);
                m.put("createTime","2022-04-19 08:38:33");
                m.put("deviceid",151235);
                m.put("gatewayno","01");
                m.put("onlineState",1);
                m.put("provinceName",12);
            }
            if (i==2){
                m.put("cityName","齐齐哈尔市");
                m.put("countyName","龙江县");
                m.put("createTime","2022-04-19 08:38:33");
                m.put("deviceid",151235);
                m.put("gatewayno","01");
                m.put("onlineState",1);
                m.put("provinceName","黑龙江省");
            }

            dataList.add(m);
        }
        JSONObject json = new JSONObject();
        json.put("list", dataList);

        return Response.build(json).success();
    }
    @BehaviourOperator(desc = "查询协议类型占比")
    @RequestMapping(value = "/typeNum")
    public Response typeNum() {
        JSONObject json = new JSONObject();
        json.put("e10", 10);
        json.put("a13",20);
        json.put("d20s", 30);
        json.put("totalNum", 60);

        return Response.build(json).success();
    }
    @BehaviourOperator(desc = "报警排名")
    @RequestMapping(value = "/rank")
    public Response rank() {
        List<HashMap> dataList=new ArrayList();

        for(int i=0; i<=5 ;i++){
            HashMap<String,Object> m=new HashMap();
            if (i==0){
                m.put("name","安徽省");
                m.put("value",123);
            }
            if (i==1){
                m.put("name","江苏省");
                m.put("value",12);
            }
            if (i==2){
                m.put("name","黑龙江省");
                m.put("value",1123);
            }
            if (i==3){
                m.put("name","吉林省");
                m.put("value",99);
            }
            if (i==4){
                m.put("name","河北省");
                m.put("value",123);
            }
            if (i==5){
                m.put("name","安徽省");
                m.put("value",1);
            }
            dataList.add(m);
        }

        return Response.build(dataList).success();
    }
    @BehaviourOperator(desc = "报警次数")
    @RequestMapping(value = "/alarmNum")
    public Response alarmNum( ) {

        List<Object> dataList=new ArrayList();
        List<Object> numList=new ArrayList();

        for(int i=0; i<=3 ;i++){
            if (i==0){

                dataList.add("2025-04");
                numList.add(348);
            }
            if (i==1){

                dataList.add("2025-05");
                numList.add(168);
            }
            if (i==2){

                dataList.add("2025-06");
                numList.add(508);
            }
            if (i==3){

                dataList.add("2025-07");
                numList.add(400);
            }
        }
        JSONObject json = new JSONObject();
        json.put("dateList", dataList);
        json.put("numList", numList);

        return Response.build(json).success();
    }
    @BehaviourOperator(desc = "查询报警记录")
    @RequestMapping(value = "/alarmRecord")
    public Response alarmRecord() {

        List<HashMap> dataList=new ArrayList();

        for(int i=0; i<=2 ;i++){
            HashMap<String,Object> m=new HashMap();
            if (i==0){
                m.put("alertdetail",12);
                m.put("alertname",12);
                m.put("alertvalue",12);
                m.put("cityName",12);
                m.put("countyName",12);
                m.put("createtime","2022-04-19 08:38:33");
                m.put("deviceid",151235);
                m.put("gatewayno","01");
                m.put("phase",12);
                m.put("provinceName",12);
                m.put("sbInfo",12);
                m.put("terminalno",12);
            }
            if (i==1){
                m.put("alertdetail",12);
                m.put("alertname",12);
                m.put("alertvalue",12);
                m.put("cityName",12);
                m.put("countyName",12);
                m.put("createtime","2022-04-19 08:38:33");
                m.put("deviceid",123124);
                m.put("gatewayno","03");
                m.put("phase",12);
                m.put("provinceName",12);
                m.put("sbInfo",12);
                m.put("terminalno",12);
            }
            if (i==2){
                m.put("alertdetail",12);
                m.put("alertname",12);
                m.put("alertvalue",12);
                m.put("cityName","齐齐哈尔市");
                m.put("countyName","龙江县");
                m.put("createtime","2022-04-19 08:38:33");
                m.put("deviceid",12);
                m.put("gatewayno","02");
                m.put("phase",12);
                m.put("provinceName","黑龙江省");
                m.put("sbInfo","485解析失败SD卡存满");
                m.put("terminalno",12);
                m.put("pressure",3.56);
                m.put("temperature",22.81);
                m.put("momentMarkCon",15392.18);
                m.put("cumulative",43816328.00);
                m.put("beforeCumulative",654321.00);

            }

            dataList.add(m);
        }
        JSONObject json = new JSONObject();
        json.put("list", dataList);
        return Response.build(json).success();
    }
    @BehaviourOperator(desc = "查询实时数据列表")
    @RequestMapping(value = "/queryRtuLatestdataList1")
    public Response queryRtuLatestdataList1(RtuDataDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<RtuDataDTO> list = rtuHisDataService.selectRtuCData(dto);
        Pagination pagination = Pagination.buildPagination(list, dto);

        return PageResponse.pageResponse(pagination, list).success();
    }
    @BehaviourOperator(desc = "查询RtuHisData列表")
    @RequestMapping(value = "/queryRtuHisDataList")
    public Response queryRtuHisDataList(RtuDataDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<RtuDataDTO> list = rtuHisDataService.findDataList(dto);
        Pagination pagination = Pagination.buildPagination(list, dto);

        return PageResponse.pageResponse(pagination, list).success();
    }
    @BehaviourOperator(desc = "查询RtuAnalogHisData列表")
    @RequestMapping(value = "/queryRtuAnalogHisDataList")
    public Response queryRtuAnalogHisDataList(RtuAnalogDataDTO dto) {
        
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<RtuAnalogDataDTO> list = rtuHisDataService.findRtuAnalogDataList(dto);
        Pagination pagination = Pagination.buildPagination(list, dto);

        return PageResponse.pageResponse(pagination, list).success();
    }
    @BehaviourOperator(desc = "查询RtuData列表")
    @RequestMapping(value = "/queryRtuDataList")
    public JSONObject queryRtuDataList(Page page, RtuOriginalData rtuOriginalData, String startTime, String endTime) {

        JSONObject json = new JSONObject();
        page = rtuDataService.queryRtuDataPage(page, rtuOriginalData, startTime, endTime);
        json.put("code", "0");
        json.put("current", page.getCurrent());
        json.put("size", page.getSize());
        json.put("total", page.getTotal());

        List<RtuOriginalData> list = page.getRecords();

        JSONArray jsonArray = new JSONArray();
        list.stream().forEach(e -> {
            JSONObject item = (JSONObject) JSONObject.toJSON(e);
            int k = 1;
            if (e.getEqType().intValue() == 1) {
                for (int i = 0; i < e.getDataBody().length() / 8; i++) {
                    String numtext = e.getDataBody().substring(i * 8, (i + 1) * 8);
                    String a = numtext.substring(6, 8);
                    String b = numtext.substring(4, 6);
                    String c = numtext.substring(2, 4);
                    String d = numtext.substring(0, 2);
                    StringBuilder sb = new StringBuilder(a);
                    sb.append(b).append(c).append(d);
                    double result = new BigDecimal(DataUtils.decodeHEX(sb.toString())).setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                    if(k==6||k==12||k==18||k==24){
                        item.put("channel" + (k), String.format("%05.5f", 0.00000d));

                    }else{
                        item.put("channel" + (k), String.format("%05.5f", result));

                    }
                    if (k==4||k==10||k==16||k==22) {
                        item.put("channel" + (k + 1), "00.00");
                       // item.put("channel" + (k + 2), "00.00");
                        k+=1;
                    }

                    System.out.println("numtext"+numtext+"k:"+k + "数："+result+"最后数："+String.format("%05.2f", result));
                    k++;
                }
                System.out.println("一个结束"+item);
                jsonArray.add(item);
            } else if (e.getEqType().intValue() == 2) {
                for (int i = 0; i < e.getDataBody().length() / 8; i++) {
                    String numtext = e.getDataBody().substring(i * 8, (i + 1) * 8);
                    item.put("channel" + (k), DataUtils.decodeHEX(numtext));
                    k++;
                }
                jsonArray.add(item);
            }else{
                for (int i = 0; i < e.getDataBody().length() / 8; i++) {
                    String numtext = e.getDataBody().substring(i * 8, (i + 1) * 8);
                    String a = numtext.substring(6, 8);
                    String b = numtext.substring(4, 6);
                    String c = numtext.substring(2, 4);
                    String d = numtext.substring(0, 2);
                    StringBuilder sb = new StringBuilder(a);
                    sb.append(b).append(c).append(d);
                    double result = new BigDecimal(DataUtils.decodeHEX(sb.toString())).setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                        item.put("channel" + (k), String.format("%05.5f", result));


                    System.out.println("numtext"+numtext+"k:"+k + "数："+result+"最后数："+String.format("%05.2f", result));
                    k++;
                }
                System.out.println("一个结束"+item);
                jsonArray.add(item);
            }

        });
        json.put("dataList", jsonArray);
        return json;
    }

    @BehaviourOperator(desc = "单一属性修改RtuData")
    @RequestMapping(value = "/updateRtuDataSingle")
    public JSONObject updateRtuDataSingle(Integer id, String column, String value) throws NoSuchFieldException, IllegalAccessException {
        JSONObject json = new JSONObject();
        RtuOriginalData rtuOriginalData = rtuDataService.getById(id);
        Class<? extends RtuOriginalData> clazz = rtuOriginalData.getClass();// 获取到对象对应的class对象
        Field nameField = clazz.getDeclaredField(column);// 获取私有成员变量:column
        nameField.setAccessible(true);// 设置操作权限为true
        nameField.set(rtuOriginalData, value);
        if (rtuDataService.updateById(rtuOriginalData)) {
            json.put("code", "0");
        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_DATABASE_ERROR_CN);
        }
        return json;
    }

    @BehaviourOperator(desc = "整体修改RtuData")
    @RequestMapping(value = "/updateRtuDataMultiple")
    public JSONObject updateRtuDataMultiple(RtuOriginalData rtuOriginalData) {
        JSONObject json = new JSONObject();

        if (rtuDataService.updateById(rtuOriginalData)) {
            json.put("code", "0");
        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_DATABASE_ERROR_CN);
        }
        return json;
    }

    @BehaviourOperator(desc = "删除RtuData")
    @RequestMapping(value = "/deleteRtuDataById")
    public JSONObject deleteRtuDataById(RtuOriginalData rtuOriginalData) {
        JSONObject json = new JSONObject();
        if (rtuDataService.deleteRtuDataById(rtuOriginalData)) {
            json.put("code", "0");
        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_DATABASE_ERROR_CN);
        }
        return json;
    }

    @BehaviourOperator(desc = "新增RtuData")
    @RequestMapping(value = "/addRtuData")
    public JSONObject addRtuData(RtuOriginalData rtuOriginalData) {
        JSONObject json = new JSONObject();
        if (rtuDataService.save(rtuOriginalData)) {
            json.put("code", "0");
        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_DATABASE_ERROR_CN);
        }
        return json;
    }
    @RequestMapping(value = "/queryDeviceDebugDataList")
    public Response queryDeviceDebugDataList(DeviceDebugDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<DeviceDebugDTO> list = deviceDebugService.findDataList(dto);
        Pagination pagination = Pagination.buildPagination(list, dto);

        return PageResponse.pageResponse(pagination, list).success();
    }
/*    @RequestMapping(value = "/realTimeQuery")
    public Response realTimeQuery(String  rtuNo) {
        //String  data="{\"CONFIG\":{\"ID\":\"12000002\",\"IP\":\"121.43.158.144\",\"PORT\":\"8082\",\"IP2\":\"112.125.89.8\",\"PORT2\":\"35316\",\"HART_DAT\":\"96442233\",\"HART_TIMER\":\"60000\",\"UPDATE_TIMER\":\"1\",\"UPDATE_DATE\":\"2022-02-08-17:46:56\"},\"MONI\":[\"12.33\",\"10.12\",\"20.23\",\"3.12\"],\"SWOUT\":[\"1\",\"0\",\"1\",\"1\"],\"SWIN\":[\"1\",\"0\",\"1\",\"1\",\"1\",\"0\",\"1\",\"1\"],\"CHANNEL\":[{\"BPS\":\"9600\",\"ISMASTER\":\"0\",\"SEACHTIMER\":\"60\",\"NODE\":[{\"SEARCHCMD\":\"060702010405\",\"NODENAME\":\"第一路流量计\",\"PASE\":[{\"HEAD\":\"010402000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"1\",\"VAL\":\"1.2\"},{\"HEAD\":\"010402000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"5\",\"VAL\":\"1.2\"},{\"HEAD\":\"010402000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"9\",\"VAL\":\"1.2\"},{\"HEAD\":\"010402000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"61\",\"VAL\":\"1.2\"},{\"HEAD\":\"010402000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"61\",\"VAL\":\"1.2\"}]},{\"SEARCHCMD\":\"060702010405\",\"NODENAME\":\"第二路流量计\",\"PASE\":[{\"HEAD\":\"010403000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"1\",\"VAL\":\"1.2\"},{\"HEAD\":\"010403000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"5\",\"VAL\":\"1.2\"},{\"HEAD\":\"010403000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"9\",\"VAL\":\"1.2\"},{\"HEAD\":\"010403000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"61\",\"VAL\":\"1.2\"},{\"HEAD\":\"010403000024F1A9010448000000000000\",\"SORT\":\"1234\",\"TYPE\":\"4F\",\"POS\":\"61\",\"VAL\":\"1.2\"}]}]}]}";
        if("".equals(rtuNo)||rtuNo==null){
            return Response.build().fail("请输入设备编号");
        }else {
            Response r=rtuDataService.getRealTimeData(rtuNo);
            if(r.getStatus()==200){
                return Response.build(JSONObject.parseObject(r.getResult().toString())).success(r.getMessage());
            }else {
                return Response.build().fail(r.getMessage());
            }
        }
    }*/
    @RequestMapping(value = "/queryRtuRunInfoList")
    public Response queryRtuRunInfoList(RtuRunInfoDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<RtuRunInfoDTO> list = rtuRunInfoService.findDataList(dto);
        Pagination pagination = Pagination.buildPagination(list, dto);

        return PageResponse.pageResponse(pagination, list).success();
    }
    @BehaviourOperator(desc = "查询点表数据")
    @RequestMapping(value = "/queryVBDataList")
    public Response queryVBDataList(RtuDataDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<VbHistory> list = vbHistoryService.findDataList(dto);
        Pagination pagination = Pagination.buildPagination(list, dto);

        return PageResponse.pageResponse(pagination, list).success();
    }
    public static String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记
        java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
        return sdf.format(date);
    }
}

